<template>
    <div class="sign-in-container">
        <el-card class="box-card">
            <div class="sign-in-body">
                <div class="sign-in-title">
                    <img src="../../assets/lyh.png" class="sign-in-logo" />
                    <span>账号注册</span>
                </div>
                <el-form :model="userInfo" ref="form" :rules="rules" label-width="0" class="sign-in-form">
                    <!-- 昵称 -->
                    <el-form-item prop="nickname">
                        <el-input v-model="userInfo.nickname" placeholder="请输入昵称" maxlength="30" clearable>
                            <template #prepend>
                                <i class="el-icon-user"></i>
                            </template>
                        </el-input>
                    </el-form-item>

                    <!-- 账号 -->
                    <el-form-item prop="accountNumber">
                        <el-input v-model="userInfo.accountNumber" placeholder="请输入账号" maxlength="16" clearable>
                            <template #prepend>
                                <i class="el-icon-phone"></i>
                            </template>
                        </el-input>
                    </el-form-item>

                    <!-- 密码 -->
                    <el-form-item prop="userPassword">
                        <el-input 
                            v-model="userInfo.userPassword"
                            placeholder="请输入密码"
                            maxlength="16"
                            show-password 
                            clearable>
                            <template #prepend>
                                <i class="el-icon-lock"></i>
                            </template>
                        </el-input>
                    </el-form-item>

                    <!-- 确认密码 -->
                    <el-form-item prop="confirmPassword">
                        <el-input 
                            v-model="userInfo.confirmPassword"
                            placeholder="请再次输入密码"
                            maxlength="16"
                            show-password 
                            clearable>
                            <template #prepend>
                                <i class="el-icon-lock"></i>
                            </template>
                        </el-input>
                    </el-form-item>
                   <!-- 邮箱输入 -->
                        <el-form-item prop="email">
                            <el-input v-model="userInfo.email" placeholder="请输入邮箱" clearable>
                            <template #prepend>
                                <i class="el-icon-message"></i>
                            </template>
                            </el-input>
                        </el-form-item>

                        <!-- 验证码输入 -->
                        <el-form-item prop="emailCode">
                            <el-input v-model="userInfo.emailCode" placeholder="请输入验证码" maxlength="6">
                            <template #prepend>
                                <i class="el-icon-key"></i>
                            </template>
                            <template #append>
                                <el-button 
                                @click="sendCode"
                                :disabled="codeSending || !userInfo.email"
                                :loading="codeSending">
                                {{ codeSending ? `${countdown}s后重试` : '获取验证码' }}
                                </el-button>
                            </template>
                            </el-input>
                        </el-form-item>
                    <!-- 提交按钮 -->
                    <div class="sign-in-submit">
                        <el-button type="primary" @click="handleSignIn">提交</el-button>
                        <el-button @click="toLogin" class="back-login">返回登录</el-button>
                    </div>
                </el-form>
            </div>
        </el-card>
    </div>
</template>

<script>
export default {
    name: "EnhancedSignIn",
    data() {
        return {
            userInfo: {
                nickname: '',
                accountNumber: '',
                userPassword: '',
                confirmPassword: '',
                email: '',
                Emailcode: ''
            },
    codeSending: false,
    countdown: 0,
            rules: {
                nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
                accountNumber: [
                                    { required: true, message: '请输入账号', trigger: 'blur' },
                                    { 
                                        pattern: /^[a-zA-Z0-9_-]{4,16}$/,
                                        message: '账号应为4-16位字母、数字或下划线',
                                        trigger: 'blur'
                                    }
                            ],
                userPassword: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 8, message: '密码长度至少8位', trigger: 'blur' },
                    {
                        pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>]).{8,}$/,
                        message: '密码至少包含字母、数字和特殊字符',
                        trigger: 'blur'
                    }
                ],
                confirmPassword: [
                            { required: true, message: '请再次输入密码', trigger: 'blur' },
                            {
                            validator: (rule, value, callback) => {
                                if (value !== this.userInfo.userPassword) {
                                callback(new Error('两次输入的密码不一致'));
                                } else {
                                callback();
                                }
                            },
                            trigger: ['blur', 'input']  // 增加 input 触发时机
                            }
                        ],
                        // 新增邮箱验证规则
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { 
            type: 'email',
            message: '请输入正确的邮箱格式',
            trigger: ['blur', 'change']
          }
        ],
        // 新增验证码规则
        emailCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { 
            pattern: /^\d{6}$/,
            message: '验证码为6位数字',
            trigger: 'blur'
          }
        ]
            }
        };
    },
    methods: {
        toLogin() {
            this.$router.replace({ path: '/login' });
        },
       // 修改原有注册方法
    handleSignIn() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            // 移除密码字段避免传到后端
            const { confirmPassword, ...submitData } = this.userInfo;
            console.log('提交数据:', submitData);
            const res = await this.$api.signIn(submitData);
            if (res.status_code === 1) {
              this.$message.success('注册成功！');
              this.resetForm();
              this.$router.replace('/login');
            } else {
              this.$message.error(res.msg || '注册失败');
            }
          } catch (error) {
            console.error('注册失败:', error);
            this.$message.error(error.response.data.msg || '网络异常');
          }
        }
      });
    },
    // 重置表单
    resetForm() {
      this.userInfo = {
        nickname: '',
        accountNumber: '',
        userPassword: '',
        confirmPassword: '',
        email: '',
        emailCode: ''
      };
      this.$refs.form.resetFields();
    },
  
 // 新增发送验证码方法
 async sendCode() {
      try {
        // 验证邮箱格式
        await this.$refs.form.validateField('email');
        
        this.codeSending = true;
        const res = await this.$api.sendCode({
          email: this.userInfo.email,
          type: 'REGISTER' // 根据后端接口定义传参
        });
        
        if (res.status_code === 1) {
          this.$message.success('验证码已发送');
          this.startCountdown();
        } else {
          this.$message.error(res.msg || '发送失败');
          this.codeSending = false;
        }
      } catch (error) {
        this.codeSending = false;
        console.error('发送验证码失败:', error);
      }
    },
    
    // 倒计时方法
    startCountdown() {
      this.countdown = 60;
      const timer = setInterval(() => {
        if (this.countdown <= 0) {
          clearInterval(timer);
          this.codeSending = false;
          return;
        }
        this.countdown--;
      }, 1000);
    },
    }
};
</script>

<style scoped>
/* 新增验证码按钮样式 */
.el-button.is-disabled {
  cursor: not-allowed;
}

/* 验证码输入框特殊样式 */
:deep(.el-input-group__append) {
  padding: 0;
  border: none;
  background: transparent;
}

:deep(.el-input-group__append .el-button) {
  padding: 0 15px;
  height: 100%;
  border-radius: 0 4px 4px 0;
}
.sign-in-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background: linear-gradient(135deg, #667eea, #764ba2);
}
.box-card {
    width: 400px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
    border-radius: 15px;
    background-color: rgba(255, 255, 255, 0.9);
    padding: 30px;
}
.sign-in-title {
    margin-bottom: 20px;
    text-align: center;
    font-size: 22px;
    color: #333;
    font-weight: 700;
}
.sign-in-logo {
    width: 50px;
    margin-bottom: 10px;
}
.sign-in-submit {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
}
.back-login {
    color: #666;
}
</style>
